package com.itwlj.service.impl;

import com.itwlj.constant.StatusConstant;
import com.itwlj.context.BaseContext;
import com.itwlj.dto.AddressBookDTO;
import com.itwlj.entity.AddressBook;
import com.itwlj.mapper.AddressBookMapper;
import com.itwlj.service.AddressBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBookDTO
     */
    public void insert(AddressBookDTO addressBookDTO) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressBookDTO, addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());

        //查询当前用户地址簿中是否有地址
        List<AddressBook> addressBookList = getByUserId(BaseContext.getCurrentId());
        if (addressBookList.isEmpty()) {
            //如果当前用户地址簿中没有地址，将新增地址设置为默认地址
            addressBook.setIsDefault(StatusConstant.STATUS_DEFAULT);
        } else {
            addressBook.setIsDefault(StatusConstant.STATUS_NOT_DEFAULT);
        }

        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据用户id查询地址簿
     *
     * @return
     */
    public List<AddressBook> getByUserId(Long userId) {
        List<AddressBook> addressBookList = addressBookMapper.getByUserId(userId);
        return addressBookList;
    }

    /**
     * 设置默认地址
     *
     * @param id
     */
    public void setDefaultAddress(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.STATUS_NOT_DEFAULT);
        //将所有地址设置为非默认地址
        addressBookMapper.update(addressBook);

        addressBook.setId(id);
        addressBook.setIsDefault(StatusConstant.STATUS_DEFAULT);
        //设置默认地址
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    /**
     * 根据id修改地址
     *
     * @param addressBookDTO
     */
    public void update(AddressBookDTO addressBookDTO) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressBookDTO, addressBook);
        addressBookMapper.update(addressBook);
    }

    /**
     * 查询用户默认地址
     *
     * @return
     */
    public AddressBook getDefaultAddress() {
        return addressBookMapper.getDefaultAddress(BaseContext.getCurrentId(), StatusConstant.STATUS_DEFAULT);
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }
}
